import { queryDictionaryApi, queryGradeApi } from "../../api/tournament"
const keyCodes = ['SWIMMING_CATEGORY', 'SWIMMING_POOL', 'DISTRICT']
Page({

  /**
   * 页面的初始数据
   */
  data: {
    projectValue: '',
    poolValue: '',
    yearValue: '',
    provinceValue: '',
    competitionYearValue: '',
    projectOptions: [],
    poolOptions: [],
    yearOptions: [],
    competitionYearOptions: [],
    provinceOptions: [],
    show: false,
    minDate: new Date(2000, 0, 1).getTime(),
    date: '出生年份',
    tabs: [{
      name: '张一鸣',
      grade: '00:22:33'
    },{
      name: '唐嫣',
      grade: '00:22:33'
    },{
      name: '成龙',
      grade: '00:22:33'
    },{
      name: '亚瑟',
      grade: '00:22:33'
    },{
      name: '石昊',
      grade: '00:22:33'
    },{
      name: '沈月',
      grade: '00:22:33'
    },{
      name: '迪丽热巴',
      grade: '00:22:33'
    },{
      name: '夏侯惇',
      grade: '00:22:33'
    }]
  },
  onSearch() {
    this.getqueryGrade()
  },
  onReset() {
    this.setData({
      projectValue: this.data.projectOptions[0].value,
      poolValue: this.data.poolOptions[0].value,
    })
    this.getqueryGrade()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    const yearOptions = this.generateRecentYears(50)
    const competitionYearOptions = this.generateRecentYears(10)
    yearOptions.unshift({ text: '出生年份', value: '' });
    competitionYearOptions.unshift({ text: '赛事年份', value: '' });
    this.setData({
      yearOptions,
      competitionYearOptions
    })
    // 封装字典请求为 Promise
    const getDict = (keyCode) => {
      return new Promise((resolve) => {
        this.getDictionary(keyCode, resolve);
      });
    };
    getDict(keyCodes[2]) // 省份字典
    // 链式调用：先执行两个字典请求，全部完成后再执行成绩查询
    Promise.all([
      getDict(keyCodes[0]), // 项目字典
      getDict(keyCodes[1])  // 池子字典
    ]).then(() => {
      // 字典数据全部获取完成后，执行成绩查询
      this.getqueryGrade()
    });
  },
  dicChange(e) {
    const detail = e.detail
    const key = e.currentTarget.dataset.key
    // 动态更新数据
    this.setData({
      [key]: detail
    })
    this.getqueryGrade()
  },
  // 获取字典数据
  async getDictionary(keyCode, resolve){
    // 项目数据
    const dicRes = await queryDictionaryApi(keyCode)
    if(dicRes.code == 0) {
      const dicData = dicRes.data
      const transformedData = dicData.map(item => ({
        value: item.valueCode,
        text: item.valueName
      }))


      switch (keyCode) {
        case keyCodes[0]:
          this.setData({
            projectOptions: transformedData,
            projectValue: transformedData[0].value
          })
          break;
        case keyCodes[1]:
          this.setData({
            poolOptions: transformedData,
            poolValue: transformedData[0].value
          })
          break;
        case keyCodes[2]:
          transformedData.unshift({text: '省份', value: ''});
          this.setData({
            provinceOptions: transformedData,
            provinceValue: transformedData[0].value
          })
          break;
        default:
          console.warn(`未知的 keyCode: ${keyCode}`);
          break;
      }
      resolve()
    }
  },
  async getqueryGrade() {
    const {projectValue = '', poolValue='', provinceValue='', competitionYearValue = '', yearValue = ''} = this.data
    const queryGradeRes = await queryGradeApi({
      project: projectValue,
      distance: poolValue,
      province: provinceValue,
      competitionYear: competitionYearValue,
      year: yearValue
    })
    console.log(queryGradeRes, 'queryGradeRes')
    if(queryGradeRes.code == 0) {
      const queryGradeList = queryGradeRes.data || []
      const sortedList = queryGradeList.sort((a, b) => a.grade - b.grade);
      this.setData({
        tabs: sortedList
      })
    }
  },
  /**
   * 生成最近 n 年的选项集合
   * @param {number} count - 需要生成的年份数量（最近多少年）
   * @returns {Array<{text: number, value: number}>} 年份选项数组
   */
  generateRecentYears(count) {
    // 获取当前年份
    const currentYear = new Date().getFullYear();
    const years = [];

    // 循环生成最近 count 年
    for (let i = 0; i < count; i++) {
      const year = currentYear - i;
      years.push({ text: year, value: year });
    }

    return years;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})